const mongoose = require("mongoose");

mongoose.connect("mongodb://127.0.0.1:27017/bilibili");

mongoose.set("strictQuery", true);
mongoose.connection.once("open", () => {
  console.log("连接成功");
  const BookSchema = new mongoose.Schema({
    name: String,
    author: String,
    price: Number,
    is_hot: Boolean,
    tags: Array,
    pub_time: Date,
    test: mongoose.Schema.Types.Mixed, // 任意类型
    // testId: mongoose.Schema.Types.ObjectId, // 外键
  });

  let BookModel = mongoose.model("books", BookSchema);

  BookModel.create(
    {
      name: "西游记",
      author: "吴承恩",
      price: 19.9,
      is_hot: true,
      tags: ["鬼怪", "励志", "社会"],
      pub_time: new Date(),
      test: "abcd",
    },
    (err, data) => {
      if (err) {
        return console.log(err);
      }
      console.log(data);
      // 关闭数据库连接(项目运行中不会添加)
      // mongoose.disconnect();
    }
  );
});

mongoose.connection.on("close", () => {
  console.log("连接关闭");
});

mongoose.connection.on("error", () => {
  console.log("连接失败");
});
